<template>
	<view class="goods-search-page">
		<!-- 顶部紫色渐变背景 -->
		<view class="top-bg">
			<view class="bg-shape bg-shape-1"></view>
			<view class="bg-shape bg-shape-2"></view>
			<view class="bg-shape bg-shape-3"></view>
		</view>

		<!-- 返回按钮 -->
		<view class="back-btn" @click="goBack">
			<image class="back-icon" src="/static/icons/back.png" mode="aspectFit"></image>
		</view>

		<scroll-view class="content" scroll-y>
			<!-- 页面标题 -->
			<view class="page-header">
				<view class="header-content">
					<text class="page-title">商品搜索</text>
					<text class="page-subtitle">发现心仪好物</text>
				</view>
			</view>

			<!-- 搜索框 -->
			<view class="search-section">
				<view class="search-box">
					<text class="search-icon">🔍</text>
					<input class="search-input" v-model="searchKeyword" placeholder="搜索商品名称或ID..."
						@confirm="handleSearch" @input="onSearchInput" />
					<view v-if="searchKeyword" class="search-clear" @click="clearSearch">
						<text>×</text>
					</view>
				</view>
			</view>

			<!-- 热门搜索 -->
			<view class="hot-search-section" v-if="!hasSearched">
				<text class="section-title">热门搜索</text>
				<view class="hot-tags">
					<view v-for="tag in hotTags" :key="tag.id" class="hot-tag" @click="searchByTag(tag.keyword)">
						<text class="tag-text">{{ tag.name }}</text>
					</view>
				</view>
			</view>

			<!-- 搜索结果 -->
			<view class="search-results" v-if="hasSearched">
				<!-- 加载状态 -->
				<view v-if="loading" class="loading-state">
					<view class="loading-spinner"></view>
					<text class="loading-text">搜索中...</text>
				</view>

				<!-- 空状态 -->
				<view v-else-if="searchResult.length === 0" class="empty-state">
					<view class="empty-icon">🔍</view>
					<text class="empty-title">抱歉未找到该商品，敬请期待</text>
					<text class="empty-desc">请尝试其他关键词或浏览热门商品</text>
					<view class="empty-action">
						<button class="action-btn" @click="clearSearch">重新搜索</button>
					</view>
				</view>

				<!-- 搜索结果列表 -->
				<view v-else class="results-list">
					<view v-for="product in searchResult" :key="product.good_id" class="product-card">
						<view class="product-header">
							<view class="product-basic">
								<text class="product-id">商品ID: {{ product.good_id }}</text>
								<text class="product-name">{{ product.good_name }}</text>
							</view>
							<view class="product-rating">
								<text class="rating-text">好评率:
									{{ (product.good_positive_review_rate * 100).toFixed(1) }}%</text>
							</view>
						</view>

						<view class="product-body">
							<view class="product-stats">
								<view class="stat-item">
									<text class="stat-label">库存</text>
									<text class="stat-value">{{ product.good_number }} 件</text>
								</view>
								<view class="stat-item">
									<text class="stat-label">销量</text>
									<text class="stat-value">{{ product.good_sell_num }} 件</text>
								</view>
								<view class="stat-item">
									<text class="stat-label">售价</text>
									<text class="stat-value price">¥{{ formatPrice(product.good_sell_price) }}</text>
								</view>
							</view>

							<view class="product-description">
								<text class="desc-label">商品描述:</text>
								<text class="desc-text">{{ product.good_description || '暂无描述' }}</text>
							</view>
						</view>

						<view class="product-footer">
							<view class="stock-status"
								:class="{ 'low-stock': product.good_number < 10, 'out-of-stock': product.good_number === 0 }">
								<text v-if="product.good_number > 0">
									{{ product.good_number < 10 ? '库存紧张' : '有货' }}
								</text>
								<text v-else>缺货</text>
							</view>
							<view class="product-actions">
								<button class="action-btn detail" @click="viewProductDetail(product)">查看详情</button>
								<!-- 添加收藏按钮 -->
								<button class="action-btn favorite" @click="addToFavorites(product)"
									:disabled="isAddingFavorite">
									{{ isAddingFavorite ? '添加中...' : '❤️ 收藏' }}
								</button>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 底部安全区域 -->
			<view class="bottom-space"></view>
		</scroll-view>

		<!-- 商品详情模态框 -->
		<view class="modal-mask" v-if="selectedProduct" @click="selectedProduct = null">
			<view class="modal-content product-detail-modal" @click.stop>
				<view class="modal-header">
					<text class="modal-title">商品详情</text>
					<text class="modal-close" @click="selectedProduct = null">×</text>
				</view>
				<view class="modal-body">
					<view class="detail-section">
						<text class="section-title">基本信息</text>
						<view class="detail-grid">
							<view class="detail-item">
								<text class="detail-label">商品ID：</text>
								<text class="detail-value">{{ selectedProduct.good_id }}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">商品名称：</text>
								<text class="detail-value">{{ selectedProduct.good_name }}</text>
							</view>
						</view>
					</view>

					<view class="detail-section">
						<text class="section-title">销售信息</text>
						<view class="sales-stats">
							<view class="stat-row">
								<text class="stat-label">当前库存</text>
								<text class="stat-value">{{ selectedProduct.good_number }} 件</text>
							</view>
							<view class="stat-row">
								<text class="stat-label">累计销量</text>
								<text class="stat-value">{{ selectedProduct.good_sell_num }} 件</text>
							</view>
							<view class="stat-row">
								<text class="stat-label">好评率</text>
								<text
									class="stat-value rating">{{ (selectedProduct.good_positive_review_rate * 100).toFixed(1) }}%</text>
							</view>
							<view class="stat-row">
								<text class="stat-label">销售价格</text>
								<text
									class="stat-value price">¥{{ formatPrice(selectedProduct.good_sell_price) }}</text>
							</view>
						</view>
					</view>

					<view class="detail-section" v-if="selectedProduct.good_description">
						<text class="section-title">商品描述</text>
						<view class="description-content">
							<text class="desc-text">{{ selectedProduct.good_description }}</text>
						</view>
					</view>
				</view>
				<view class="modal-footer">
					<!-- 添加收藏按钮 -->
					<button class="modal-button favorite" @click="addToFavorites(selectedProduct)"
						:disabled="isAddingFavorite">
						{{ isAddingFavorite ? '添加中...' : '❤️ 加入收藏' }}
					</button>
					<button class="modal-button confirm" @click="selectedProduct = null">关闭</button>
				</view>
			</view>
		</view>

		<!-- 加载遮罩 -->
		<view class="loading-mask" v-if="globalLoading">
			<view class="loading-spinner"></view>
			<text class="loading-text">处理中...</text>
		</view>
	</view>
</template>

<script>
	const API_BASE_URL = 'http://localhost:8000/api/v1';

	export default {
		name: 'GoodsSearch',
		data() {
			return {
				searchKeyword: '',
				loading: false,
				globalLoading: false,
				hasSearched: false,
				searchResult: [],
				selectedProduct: null,
				hotTags: [{
						id: 1,
						name: '华为路由器',
						keyword: '华为'
					},
					{
						id: 2,
						name: '小米扫地机器人',
						keyword: '小米'
					},
					{
						id: 3,
						name: '苹果电脑',
						keyword: '苹果'
					},
					{
						id: 4,
						name: '戴尔显示器',
						keyword: '显示器'
					},
					{
						id: 5,
						name: '联想笔记本',
						keyword: '联想'
					}
				],
				searchTimer: null,
				isAddingFavorite: false
			};
		},
		computed: {
			token() {
				return uni.getStorageSync('token');
			}
		},
		onLoad() {
			console.log('商品搜索页面加载');
		},
		methods: {
			// 返回首页
			goBack() {
				uni.switchTab({
					url: '/pages/home/home'
				});
			},

			// 搜索输入处理
			onSearchInput() {
				clearTimeout(this.searchTimer);
			},

			// 处理搜索
			async handleSearch() {
				if (!this.searchKeyword.trim()) {
					uni.showToast({
						title: '请输入搜索关键词',
						icon: 'none'
					});
					return;
				}

				this.loading = true;
				this.hasSearched = true;

				try {
					let url = `${API_BASE_URL}/goods/search?`;

					// 判断是ID搜索还是关键词搜索
					if (/^\d+$/.test(this.searchKeyword.trim())) {
						// 纯数字，按商品ID搜索
						url += `good_id=${parseInt(this.searchKeyword.trim())}`;
					} else {
						// 关键词搜索
						url += `keyword=${encodeURIComponent(this.searchKeyword.trim())}`;
					}

					console.log('搜索URL:', url);

					const response = await new Promise((resolve, reject) => {
						uni.request({
							url: url,
							method: 'GET',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							success: resolve,
							fail: reject
						});
					});

					console.log('搜索响应:', response);

					if (response.statusCode === 200) {
						const data = response.data;
						this.searchResult = data.goods || [];
						console.log('搜索结果:', this.searchResult);
					} else if (response.statusCode === 404) {
						this.searchResult = [];
						console.log('未找到相关商品');
					} else {
						throw new Error(response.data.detail || '搜索失败');
					}
				} catch (error) {
					console.error('搜索商品失败:', error);
					this.searchResult = [];
					uni.showToast({
						title: error.message || '搜索失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 通过热门标签搜索
			searchByTag(keyword) {
				this.searchKeyword = keyword;
				this.handleSearch();
			},

			// 清除搜索
			clearSearch() {
				this.searchKeyword = '';
				this.hasSearched = false;
				this.searchResult = [];
			},

			// 查看商品详情
			viewProductDetail(product) {
				this.selectedProduct = product;
			},

			// 添加收藏
			async addToFavorites(product) {
				if (this.isAddingFavorite) return;

				this.isAddingFavorite = true;
				try {
					const favoriteData = {
						good_id: product.good_id
					};

					console.log('添加收藏数据:', favoriteData);

					const response = await new Promise((resolve, reject) => {
						uni.request({
							url: `${API_BASE_URL}/users/favorites`,
							method: 'POST',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							data: favoriteData,
							success: resolve,
							fail: reject
						});
					});

					if (response.statusCode === 200) {
						uni.showToast({
							title: '收藏成功',
							icon: 'success'
						});
						// 关闭商品详情模态框（如果打开的话）
						if (this.selectedProduct) {
							this.selectedProduct = null;
						}
					} else if (response.statusCode === 400) {
						// 处理商品已在收藏夹中的情况
						const errorMsg = response.data.detail || '收藏失败';
						if (errorMsg.includes('已在收藏夹中')) {
							uni.showToast({
								title: '该商品已经收藏',
								icon: 'none',
								duration: 2000
							});
						} else {
							throw new Error(errorMsg);
						}
					} else {
						throw new Error(response.data.detail || '收藏失败');
					}
				} catch (error) {
					console.error('收藏失败:', error);
					// 检查错误信息是否包含"已在收藏夹中"
					if (error.message && error.message.includes('已在收藏夹中')) {
						uni.showToast({
							title: '该商品已经收藏',
							icon: 'none',
							duration: 2000
						});
					} else {
						uni.showToast({
							title: error.message || '收藏失败',
							icon: 'none'
						});
					}
				} finally {
					this.isAddingFavorite = false;
				}
			},

			// 格式化价格
			formatPrice(price) {
				if (!price) return '0.00';
				return parseFloat(price).toFixed(2);
			}
		}
	};
</script>

<style scoped>
	.goods-search-page {
		position: relative;
		min-height: 100vh;
		background: linear-gradient(180deg, #f9f7ff 0%, #f0ebff 100%);
	}

	.top-bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 300rpx;
		background: linear-gradient(135deg, #8A2BE2 0%, #9370DB 50%, #DA70D6 100%);
		z-index: 0;
		overflow: hidden;
	}

	.bg-shape {
		position: absolute;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.1);
	}

	.bg-shape-1 {
		width: 200rpx;
		height: 200rpx;
		top: -100rpx;
		right: -50rpx;
	}

	.bg-shape-2 {
		width: 150rpx;
		height: 150rpx;
		bottom: 30rpx;
		left: -60rpx;
	}

	.bg-shape-3 {
		width: 100rpx;
		height: 100rpx;
		top: 80rpx;
		left: 25%;
	}

	/* 返回按钮 */
	.back-btn {
		position: fixed;
		top: 80rpx;
		left: 30rpx;
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.9);
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
		z-index: 1000;
		backdrop-filter: blur(10px);
	}

	.back-icon {
		width: 32rpx;
		height: 32rpx;
	}

	.content {
		position: relative;
		z-index: 1;
		height: 100vh;
		padding: 30rpx 24rpx;
		box-sizing: border-box;
	}

	.page-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		padding-top: 40rpx;
	}

	.header-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}

	.page-title {
		font-size: 40rpx;
		font-weight: 700;
		color: #333;
		display: block;
		margin-bottom: 8rpx;
	}

	.page-subtitle {
		font-size: 26rpx;
		color: #666;
		display: block;
	}

	/* 搜索框样式 */
	.search-section {
		margin-bottom: 40rpx;
	}

	.search-box {
		position: relative;
		background: rgba(255, 255, 255, 0.9);
		border-radius: 20rpx;
		padding: 20rpx 24rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 4rpx 16rpx rgba(138, 43, 226, 0.1);
		border: 1rpx solid rgba(255, 255, 255, 0.6);
	}

	.search-icon {
		font-size: 28rpx;
		color: #999;
		margin-right: 16rpx;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.search-input::placeholder {
		color: #999;
	}

	.search-clear {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background: #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #999;
	}

	/* 热门搜索 */
	.hot-search-section {
		margin-bottom: 30rpx;
	}

	.section-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
		display: block;
		margin-bottom: 20rpx;
	}

	.hot-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}

	.hot-tag {
		padding: 16rpx 24rpx;
		background: rgba(255, 255, 255, 0.9);
		border-radius: 20rpx;
		border: 1rpx solid #e0e0e0;
	}

	.tag-text {
		font-size: 26rpx;
		color: #666;
	}

	.hot-tag:active {
		background: #f0f0f0;
		transform: scale(0.98);
	}

	/* 商品卡片样式 */
	.product-card {
		background: rgba(255, 255, 255, 0.9);
		border-radius: 24rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		backdrop-filter: blur(10px);
		box-shadow: 0 6rpx 24rpx rgba(138, 43, 226, 0.1);
		border: 1rpx solid rgba(255, 255, 255, 0.6);
	}

	.product-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.product-basic {
		flex: 1;
	}

	.product-id {
		font-size: 24rpx;
		color: #888;
		display: block;
		margin-bottom: 8rpx;
	}

	.product-name {
		font-size: 30rpx;
		font-weight: 600;
		color: #333;
		display: block;
	}

	.product-rating {
		flex-shrink: 0;
	}

	.rating-text {
		font-size: 24rpx;
		color: #ff6b35;
		font-weight: 500;
	}

	.product-body {
		margin-bottom: 24rpx;
	}

	.product-stats {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr;
		gap: 16rpx;
		margin-bottom: 20rpx;
	}

	.stat-item {
		text-align: center;
		padding: 16rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
	}

	.stat-label {
		font-size: 22rpx;
		color: #666;
		display: block;
		margin-bottom: 4rpx;
	}

	.stat-value {
		font-size: 24rpx;
		color: #333;
		font-weight: 600;
		display: block;
	}

	.stat-value.price {
		color: #ff6b35;
	}

	.product-description {
		padding: 16rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
	}

	.desc-label {
		font-size: 24rpx;
		color: #666;
		font-weight: 500;
		display: block;
		margin-bottom: 8rpx;
	}

	.desc-text {
		font-size: 24rpx;
		color: #333;
		line-height: 1.4;
	}

	.product-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 20rpx;
		border-top: 1rpx solid #f0f0f0;
	}

	.stock-status {
		padding: 8rpx 16rpx;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	.stock-status:not(.low-stock):not(.out-of-stock) {
		background: #e8f5e8;
		color: #2e7d32;
	}

	.stock-status.low-stock {
		background: #fff3e0;
		color: #ef6c00;
	}

	.stock-status.out-of-stock {
		background: #ffebee;
		color: #d32f2f;
	}

	.product-actions {
		display: flex;
		gap: 16rpx;
	}

	.action-btn.detail {
		padding: 12rpx 24rpx;
		background: linear-gradient(135deg, #8A2BE2, #9370DB);
		color: white;
		border: none;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	.action-btn.favorite {
		padding: 12rpx 24rpx;
		background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
		color: white;
		border: none;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	.action-btn:disabled {
		background: #ccc;
		color: #999;
	}

	.action-btn.detail:active,
	.action-btn.favorite:active {
		transform: scale(0.95);
	}

	/* 加载状态 */
	.loading-state,
	.empty-state {
		text-align: center;
		padding: 120rpx 0;
	}

	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid #f3f3f3;
		border-top: 4rpx solid #8A2BE2;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin: 0 auto 20rpx;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.loading-text {
		font-size: 28rpx;
		color: #666;
	}

	.empty-icon {
		font-size: 80rpx;
		margin-bottom: 20rpx;
		display: block;
	}

	.empty-title {
		font-size: 32rpx;
		color: #333;
		display: block;
		margin-bottom: 12rpx;
		font-weight: 600;
	}

	.empty-desc {
		font-size: 26rpx;
		color: #888;
		line-height: 1.5;
	}

	.empty-action {
		margin-top: 30rpx;
	}

	.action-btn {
		padding: 20rpx 40rpx;
		background: linear-gradient(135deg, #8A2BE2, #9370DB);
		color: white;
		border: none;
		border-radius: 12rpx;
		font-size: 26rpx;
	}

	.action-btn:active {
		transform: scale(0.98);
	}

	/* 模态框样式 */
	.modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 2000;
		padding: 40rpx;
	}

	.modal-content {
		background: white;
		border-radius: 24rpx;
		width: 100%;
		max-width: 600rpx;
		max-height: 80vh;
		overflow: hidden;
		box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.2);
	}

	.product-detail-modal {
		max-width: 560rpx;
		max-height: 70vh;
		display: flex;
		flex-direction: column;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 40rpx 32rpx 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
		flex-shrink: 0;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.modal-close {
		font-size: 40rpx;
		color: #999;
		padding: 10rpx;
	}

	.modal-body {
		padding: 32rpx;
		flex: 1;
		overflow-y: auto;
	}

	.detail-section {
		margin-bottom: 32rpx;
	}

	.section-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
		display: block;
		margin-bottom: 20rpx;
	}

	.detail-grid {
		display: grid;
		gap: 16rpx;
	}

	.detail-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.detail-label {
		font-size: 26rpx;
		color: #666;
	}

	.detail-value {
		font-size: 26rpx;
		color: #333;
		font-weight: 500;
	}

	.sales-stats {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.stat-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16rpx 20rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
	}

	.stat-label {
		font-size: 26rpx;
		color: #666;
	}

	.stat-value {
		font-size: 26rpx;
		color: #333;
		font-weight: 600;
	}

	.stat-value.rating {
		color: #ff6b35;
	}

	.stat-value.price {
		color: #ff6b35;
		font-size: 28rpx;
	}

	.description-content {
		padding: 20rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
	}

	.desc-text {
		font-size: 26rpx;
		color: #333;
		line-height: 1.5;
	}

	.modal-footer {
		display: flex;
		padding: 0 32rpx 32rpx;
		gap: 20rpx;
		flex-shrink: 0;
	}

	.modal-button {
		flex: 1;
		padding: 24rpx;
		border: none;
		border-radius: 12rpx;
		font-size: 28rpx;
		font-weight: 500;
	}

	.modal-button.favorite {
		background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
		color: white;
	}

	.modal-button.confirm {
		background: linear-gradient(135deg, #8A2BE2, #9370DB);
		color: white;
	}

	.modal-button:disabled {
		background: #ccc;
		color: #999;
	}

	.modal-button.confirm:active,
	.modal-button.favorite:active {
		transform: scale(0.98);
	}

	/* 全局加载遮罩 */
	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0.9);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		z-index: 3000;
	}

	.bottom-space {
		height: 40rpx;
	}
</style>